<template>
  <div class="tally-form">
    <!-- 顶部导航栏 使用Vant NavBar -->
    <van-nav-bar
      title="记一笔"
      left-text="返回"
      left-arrow
      @click-left="handleGoBack"
    >
      <template #right>
        <!-- 账本选择器 -->
        <div class="account-selector" @click="handleAccountSelectorClick" v-if="accountList.length > 0">
          <span class="account-name">{{ currentAccountName }}</span>
          <van-icon name="arrow-down" size="12" />
        </div>
      </template>
    </van-nav-bar>

    <!-- 收支方向切换 使用Vant Tabs -->
    <van-tabs 
      v-model:active="activeDirection" 
      color="#ffd64f" 
      title-active-color="#333"
      @change="onDirectionChange"
      class="direction-tabs"
    >
      <van-tab title="支出" :name="0"></van-tab>
      <van-tab title="收入" :name="1"></van-tab>
    </van-tabs>

    <!-- 分类选择区域 使用Vant Grid -->
    <div class="category-section">
      <div class="section-title">
        <van-icon :name="activeDirection === 0 ? 'balance-list-o' : 'gold-coin-o'" class="title-icon" />
        <span>{{ activeDirection === 0 ? '支出分类' : '收入分类' }}</span>
      </div>
      <van-grid :column-num="4" :border="false" :gutter="8">
        <van-grid-item 
          v-for="item in currentCategoryList" 
          :key="item.id"
          @click="selectCategory(item)"
          class="category-grid-item"
          :class="{ 'selected': selectedCategory && selectedCategory.id === item.id }"
        >
          <template #icon>
            <div 
              class="category-icon-wrapper"
              :style="{ 
                backgroundColor: item.color ? item.color + '20' : '#FFF3E1',
                borderColor: item.color || '#FFB300'
              }"
            >
              <van-icon 
                :name="item.icon" 
                :color="item.color || '#FFB300'"
                size="26"
              />
            </div>
          </template>
          <template #text>
            <span class="category-text">{{ item.name }}</span>
          </template>
        </van-grid-item>
      </van-grid>
    </div>

    <!-- 金额和备注输入区（选择分类后显示） -->
    <div v-show="showInputArea" class="input-section">
      <!-- 金额显示 -->
      <van-cell-group inset>
        <van-cell title="金额" :value="'¥' + displayExpression" class="amount-cell" />
        <van-field
          v-model="remark"
          rows="2"
          autosize
          type="textarea"
          maxlength="100"
          placeholder="添加备注..."
          show-word-limit
        />
        <van-cell 
          title="日期" 
          :value="formatDateDisplay" 
          is-link 
          @click="showDatePicker = true" 
          class="date-cell"
        />
      </van-cell-group>

      <!-- 保存按钮 -->
      <div class="save-btn-wrapper">
        <van-button 
          type="primary" 
          size="large" 
          block 
          round
          @click="saveRecord"
          :disabled="!canSave"
          class="save-btn"
        >
          保存记账
        </van-button>
      </div>
    </div>

    <!-- Vant NumberKeyboard 数字键盘 -->
    <van-number-keyboard
      v-model="currentExpression"
      :show="showKeyboard"
      extra-key="."
      close-button-text="完成"
      @blur="showKeyboard = false"
      @input="onKeyboardInput"
      @delete="onKeyboardDelete"
    />

    <!-- Vant Calendar 日历选择器 -->
    <van-calendar 
      v-model:show="showDatePicker" 
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="onDateConfirm"
    />

    <!-- 账本选择器弹窗 -->
    <van-popup v-model:show="showAccountPicker" position="bottom" round>
      <van-picker
        :columns="accountColumns"
        @confirm="onAccountConfirm"
        @cancel="showAccountPicker = false"
        :default-index="currentAccountIndex"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { categories } from '@/utils/categoryData';
import { saveTallyRecord } from '@/api/index';
import { showToast, showSuccessToast, showConfirmDialog } from 'vant';
import { useAccountStore } from '@/stores/account';

const router = useRouter();
const route = useRoute();
const accountStore = useAccountStore();

// 状态管理
const activeDirection = ref(0); // 0=支出, 1=收入
const showKeyboard = ref(false);
const showInputArea = ref(false);
const showDatePicker = ref(false);
const showAccountPicker = ref(false);
const selectedDateTime = ref(new Date()); // 选中的日期
const currentExpression = ref('0'); // 金额表达式
const remark = ref('');
const selectedCategory = ref(null);

// 日期范围限制
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2030, 11, 31);

// 账本相关
const accountList = computed(() => accountStore.accountList);
const currentAccount = computed(() => accountStore.currentAccount);

// 当前账本名称
const currentAccountName = computed(() => {
  return currentAccount.value ? currentAccount.value.remark : '选择账本';
});

// 账本选择器列数据
const accountColumns = computed(() => {
  return accountList.value.map(account => ({
    text: account.remark,
    value: account.id
  }));
});

// 当前账本在列表中的索引
const currentAccountIndex = computed(() => {
  if (!currentAccount.value) return 0;
  return accountList.value.findIndex(a => a.id === currentAccount.value.id);
});

// 使用共享的分类数据
const currentCategoryList = computed(() => {
  return activeDirection.value === 0 ? categories.value.expense : categories.value.income;
});

// 计算属性
const displayExpression = computed(() => {
  if (currentExpression.value === '' || currentExpression.value === '0') {
    return '0.00';
  }
  const num = parseFloat(currentExpression.value);
  return isNaN(num) ? '0.00' : num.toFixed(2);
});

const formatDateDisplay = computed(() => {
  const date = selectedDateTime.value;
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  // 判断是否为今天
  const today = new Date();
  const isToday = date.getDate() === today.getDate() &&
                  date.getMonth() === today.getMonth() &&
                  date.getFullYear() === today.getFullYear();
  
  return isToday ? '今天' : `${year}-${month}-${day}`;
});

const canSave = computed(() => {
  const price = parseFloat(currentExpression.value);
  return !isNaN(price) && price > 0 && selectedCategory.value;
});

// 方法实现
const onDirectionChange = () => {
  selectedCategory.value = null;
  resetCalculator();
  showInputArea.value = false;
  showKeyboard.value = false;
};

const selectCategory = (item) => {
  if (item.id === 999) {
    router.push('/category-settings');
    return;
  }
  
  selectedCategory.value = item;
  showInputArea.value = true;
  showKeyboard.value = true;
};

const onKeyboardInput = (key) => {
  if (currentExpression.value === '0') {
    currentExpression.value = key;
  } else {
    // 限制小数点后两位
    if (key === '.' && currentExpression.value.includes('.')) {
      return;
    }
    if (currentExpression.value.includes('.')) {
      const parts = currentExpression.value.split('.');
      if (parts[1] && parts[1].length >= 2) {
        return;
      }
    }
    currentExpression.value += key;
  }
};

const onKeyboardDelete = () => {
  if (currentExpression.value.length === 1) {
    currentExpression.value = '0';
  } else {
    currentExpression.value = currentExpression.value.slice(0, -1);
  }
};

const resetCalculator = () => {
  currentExpression.value = '0';
};

const resetAll = () => {
  resetCalculator();
  selectedCategory.value = null;
  remark.value = '';
  selectedDateTime.value = new Date();
  showInputArea.value = false;
  showKeyboard.value = false;
};

const onDateConfirm = (date) => {
  selectedDateTime.value = date;
  showDatePicker.value = false;
  const month = date.getMonth() + 1;
  const day = date.getDate();
  showToast(`已选择: ${month}月${day}日`);
};

// 点击账本选择器
const handleAccountSelectorClick = () => {
  console.log('点击账本选择器，账本数量:', accountList.value.length);
  
  if (accountList.value.length === 0) {
    showConfirmDialog({
      title: '提示',
      message: '你还没有账本，是否跳转到账本页添加账本？',
      confirmButtonText: '去添加',
      cancelButtonText: '取消',
    })
      .then(() => {
        // 点击确认，跳转到账本管理页面
        router.push('/ledger');
      })
      .catch(() => {
        // 点击取消，不做任何操作
      });
    return;
  }
  
  showAccountPicker.value = true;
};

// 确认选择账本
const onAccountConfirm = ({ selectedOptions }) => {
  const selected = selectedOptions[0];
  const account = accountList.value.find(a => a.id === selected.value);
  if (account) {
    accountStore.setCurrentAccount(account);
    showToast(`已切换到：${account.remark}`);
  }
  showAccountPicker.value = false;
};

const saveRecord = () => {
  // 验证金额
  const price = parseFloat(currentExpression.value);
  if (isNaN(price) || price <= 0) {
    showToast('请输入有效的金额');
    return;
  }

  if (!selectedCategory.value) {
    showToast('请选择分类');
    return;
  }

  // 验证账本
  if (!currentAccount.value) {
    showToast('请先选择账本');
    showAccountPicker.value = true;
    return;
  }

  // 构建请求数据
  const record = {
    type: activeDirection.value + 1, // 1=支出, 2=收入
    flag: selectedCategory.value.id,
    price: price,
    remark: remark.value,
    accountId: currentAccount.value.id, // 账本ID
    createTime: selectedDateTime.value.getTime()
  };
  
  console.log('保存记账记录:', record);
  console.log('选择的账本:', currentAccount.value);

  // 调用API
  saveTallyRecord(record)
    .then(() => {
      showSuccessToast('记账成功');
      resetAll();
      // 延迟跳转到明细页面，让用户看到成功提示
      setTimeout(() => {
        router.push('/detail');
      }, 500);
    })
    .catch(error => {
      console.error('保存失败:', error);
      showToast(error.message || '保存失败，请重试');
    });
};

const handleGoBack = () => {
  resetAll();
  router.back();
};

// 初始化账本数据的函数
const initAccountData = async () => {
  console.log('开始初始化账本数据...');
  
  // 恢复上次选择的账本
  accountStore.restoreCurrentAccount();
  console.log('恢复的账本:', currentAccount.value);
  
  // 刷新账本列表（每次都重新加载以获取最新数据）
  console.log('刷新账本列表...');
  await accountStore.refreshAccountList();
  
  console.log('账本列表:', accountList.value);
  console.log('当前账本:', currentAccount.value);
  
  // 如果没有账本，弹出确认对话框
  if (accountList.value.length === 0) {
    showConfirmDialog({
      title: '提示',
      message: '你还没有账本，是否跳转到账本页添加账本？',
      confirmButtonText: '去添加',
      cancelButtonText: '取消',
      closeOnClickOverlay: false, // 不允许点击遮罩关闭
    })
      .then(() => {
        // 点击确认，跳转到账本管理页面
        router.push('/ledger');
      })
      .catch(() => {
        // 点击取消，返回上一页
        router.back();
      });
  }
};

// 监听路由变化，从账本页返回时刷新
watch(() => route.path, (newPath, oldPath) => {
  if (newPath === '/tallyForm' && oldPath === '/ledger') {
    console.log('从账本页返回，刷新账本数据');
    initAccountData();
  }
});

// 组件挂载时加载账本列表
onMounted(async () => {
  console.log('TallyForm页面 onMounted');
  await initAccountData();
});
</script>

<style scoped>
.tally-form {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 20px;
}

/* 导航栏样式 */
:deep(.van-nav-bar) {
  background: linear-gradient(135deg, #ffd844, #ffc107);
}

:deep(.van-nav-bar__title) {
  color: #333;
  font-weight: bold;
  font-size: 18px;
}

:deep(.van-nav-bar__text) {
  color: #333;
}

:deep(.van-nav-bar .van-icon) {
  color: #333;
}

/* 账本选择器 */
.account-selector {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.2s;
  margin-right: 8px;
}

.account-selector:active {
  background: rgba(255, 255, 255, 0.5);
  transform: scale(0.98);
}

.account-name {
  font-size: 13px;
  color: #333;
  margin-right: 4px;
  font-weight: 500;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 收支方向标签 */
.direction-tabs {
  background: linear-gradient(135deg, #ffd844, #ffc107);
  padding: 0 16px 16px;
}

:deep(.van-tabs__wrap) {
  background: transparent;
}

:deep(.van-tabs__nav) {
  background: rgba(255, 255, 255, 0.5);
  border-radius: 20px;
  padding: 4px;
}

:deep(.van-tab) {
  color: rgba(0, 0, 0, 0.6);
  font-size: 15px;
  border-radius: 16px;
  transition: all 0.3s ease;
}

:deep(.van-tab--active) {
  background-color: #fff;
  color: #333;
  font-weight: 600;
}

:deep(.van-tabs__line) {
  display: none;
}

/* 分类选择区域 */
.category-section {
  padding: 16px;
  background: #fff;
  margin: 12px;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f5f5f5;

  .title-icon {
    font-size: 18px;
    color: #ffc107;
  }
}

:deep(.van-grid-item__content) {
  padding: 14px 8px;
  background-color: transparent;
}

.category-grid-item {
  position: relative;
  transition: all 0.3s ease;
}

.category-grid-item::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 0;
  height: 0;
  background: rgba(255, 193, 7, 0.1);
  border-radius: 12px;
  transition: all 0.3s ease;
  z-index: 0;
}

.category-grid-item:active::before {
  width: calc(100% - 8px);
  height: calc(100% - 8px);
}

.category-grid-item.selected::after {
  content: '';
  position: absolute;
  top: 6px;
  right: 6px;
  width: 8px;
  height: 8px;
  background: #ffc107;
  border-radius: 50%;
  z-index: 2;
  box-shadow: 0 2px 4px rgba(255, 193, 7, 0.4);
}

.category-icon-wrapper {
  width: 54px;
  height: 54px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 16px;
  margin: 0 auto 8px;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
}

.category-grid-item:active .category-icon-wrapper {
  transform: scale(0.92);
}

.category-grid-item.selected .category-icon-wrapper {
  border-width: 2.5px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.category-text {
  font-size: 12px;
  color: #666;
  font-weight: 500;
  position: relative;
  z-index: 1;
}

/* 输入区域 */
.input-section {
  padding: 0 12px 16px;
}

:deep(.van-cell-group) {
  margin-bottom: 16px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.van-cell) {
  padding: 14px 16px;
}

.amount-cell {
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
}

:deep(.amount-cell .van-cell__title) {
  color: #666;
}

:deep(.amount-cell .van-cell__value) {
  color: #f57c00;
  font-size: 26px;
  font-weight: bold;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

:deep(.van-field__label) {
  color: #666;
  font-weight: 500;
}

:deep(.van-field__control) {
  color: #333;
  font-size: 14px;
}

.date-cell {
  color: #666;
}

:deep(.date-cell .van-icon) {
  color: #ffc107;
}

/* 保存按钮 */
.save-btn-wrapper {
  padding: 8px 0;
  position: relative;
}

.save-btn {
  background: linear-gradient(135deg, #ffd844, #ffc107);
  border: none;
  color: #333;
  font-weight: bold;
  font-size: 17px;
  height: 48px;
  box-shadow: 0 6px 20px rgba(255, 193, 7, 0.35);
  position: relative;
  overflow: hidden;
}

.save-btn::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s;
}

.save-btn:active::before {
  width: 300px;
  height: 300px;
}

.save-btn:active {
  transform: scale(0.98);
}

:deep(.save-btn.van-button--disabled) {
  background: #e0e0e0;
  box-shadow: none;
  color: #999;
}
</style>
